<script>
export default {
  name:"depotManage",
  data() {
    return {
      tableData: [],
      hashMapStaff:{},
      pageNum:1,
      pageSize:5,
      total:5,
      name:'',
      remark:'',
      dialogVisible:false,
      loading: true,
      form:{
        id:'',
        name:'',
        address:'',
        type:'',
        sort:'',
        remark:'',
        principal:'',
        status:''
      },
      rules: {
        name: [
          { required: true, message: '请输入仓库名称', trigger: 'blur' },
         ]
      }
    };
  },
  methods:{
    loadOption(){
      this.$axios.get('/zzh-depot/option').then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.hashMapStaff = res.data.hashMapStaff;
        }else {
          alert('获取数据失败')
        }
      })
    },
    loadPost(){
      this.loading = true;
      this.$axios.post('/zzh-depot/list',{
        page:this.pageNum,
        limit:this.pageSize,
        name:this.name,
        remark:this.remark
      }).then(res=>res.data).then(res=>{
        this.loading = false;
        if(res.resultCode==200){
          this.tableData=res.data
          this.total=res.total
        }else {
          alert('获取数据失败')
        }
      })
    },
    //导出数据
    exportExcel() {
      //将响应数据类型设置为 Blob 对象   原因: 确保文件等二进制数据在传输过程中不会被转换或解析,对于文件下载非常有用，因为你可以直接将返回的二进制数据用于创建可下载的文件
      this.$axios.post('/zzh-excel/depotExcel',this.tableData, { responseType: 'blob' })
          .then(response => {
            // 将获取到的Excel数据转换为文件
            //Blob是二进制的容器，可以存放任意类型的二进制文件：图片/音频/文件
            //type : 类型设为Excel文件（.xlsx）的MIME类型，告诉浏览器创建的是一个Excel文件，默认使用excel打开
            const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

            // 创建隐藏的下载链接并模拟点击下载
            const link = document.createElement('a');
            //创建一个可供用户下载的链接
            link.href = URL.createObjectURL(blob);
            link.download = '仓库信息表格.xlsx';
            //设置链接的打开方式为新标签页（_blank），这样用户点击链接后会在新标签页中下载文件
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          })
          .catch(error => {
            console.error(error);
          });
    },
    add(){
      console.log("add")
      this.dialogVisible=true
      this.$nextTick(()=>{
        this.resetForm()
      })
    },
    loadAdd(){
      //表单验证
      this.$refs.form.validate((valid) => {
        console.log(this.form.id)
        if (valid) {
          if(this.form.id){
            this.doUpdate();
          }else {
            console.log("doAdd")
            this.doAdd()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    doAdd(){
      this.$axios.post('/zzh-depot/add',this.form).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.dialogVisible=false
          this.$message({
            showClose: true,
            message: '新增数据成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '新增数据失败',
            type: 'error'
          });
        }
      })
    },
    mod(row){
      this.dialogVisible=true
      this.$nextTick(()=>{
        this.form.id=row.id
        this.form.name=row.name
        this.form.address=row.address
        this.form.type=row.type
        this.form.sort=row.sort
        this.form.remark=row.remark
        this.form.principal=row.principal
        this.form.status=row.status
      })
    },
    doUpdate(){
      this.$axios.put('/zzh-depot/update',this.form).then(res=>res.data).then(res=>{
        this.form.id=''
        if(res.resultCode==200){
          this.dialogVisible=false
          this.$message({
            showClose: true,
            message: '更新数据成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '更新数据失败',
            type: 'error'
          });
        }
      })
    },
    del(id){
      this.$axios.delete('/zzh-depot/delete?id='+id).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '删除失败',
            type: 'error'
          });
        }
      })
    },
    updateStatus(id){
      this.$axios.put('/zzh-depot/updateStatus?id='+id).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.$message({
            showClose: true,
            message: '更新状态成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '更新状态失败',
            type: 'error'
          });
        }
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum=1
      this.pageSize=val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum=val
      this.loadPost()
    },
    getPositionName(id){
      return this.hashMapStaff[id] || '';
    },
    resetParam(){
      this.name=''
      this.remark=''
      this.loadPost()
    },
    resetForm() {
      //重置窗体
      this.$refs.form.resetFields();
    }
  },
  beforeMount() {
    this.loadOption();
    this.loadPost();
  }
}
</script>

<template>
  <div>
    <!--    按钮-->
    <div style="margin-bottom: 5px">
      仓库名称：
      <el-input v-model="name" placeholder="请输入仓库名称" suffix-icon="el-icon-search" style="width: 200px"
                @keyup.enter.native="loadPost"></el-input>
      备注：
      <el-input v-model="remark" placeholder="请输入备注" suffix-icon="el-icon-search" style="width: 200px"
                @keyup.enter.native="loadPost"></el-input>

      <el-button type="primary" style="margin-left: 5px" @click="loadPost">查询</el-button>
      <el-button type="success" @click="resetParam">重置</el-button>
      <el-button type="primary" style="margin-left: 5px" @click="add">新增</el-button>
      <el-button type="success" plain @click="exportExcel" style="margin-left: 10px" icon="el-icon-download">导出Excel</el-button>
    </div>
    <!--    表单-->
    <el-table :data="tableData" v-loading="loading"
              :header-cell-style="{background:'#f3f6fd',color:'#555'}">
      <el-table-column prop="id" label="id" width="140">
      </el-table-column>
      <el-table-column prop="name" label="仓库名称" width="140">
      </el-table-column>
      <el-table-column prop="address" label="仓库地址" width="120">
      </el-table-column>
<!--      <el-table-column prop="sort" label="排序" width="120">-->
<!--      </el-table-column>-->
      <el-table-column prop="remark" label="描述" width="120">
      </el-table-column>
      <el-table-column prop="principal" label="负责人" width="120">
        <template slot-scope="scope">
          {{ getPositionName(scope.row.principal) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-tag
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              disable-transitions>{{scope.row.status === 1 ? '正常' : scope.row.status === 2 ? '禁用' : '已删除'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="operate" label="操作">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm
              title="确定删除吗？"
              style="margin-left: 5px;margin-right: 5px"
              @confirm="del(scope.row.id)"
          >
            <el-button slot="reference" size="small" type="danger">删除</el-button>
          </el-popconfirm>
          <el-button size="small" type="success" @click="updateStatus(scope.row.id)">启用/禁用</el-button>

        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    <!--    提示框-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="40%"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="mini">
        <el-form-item label="仓库名称：" prop="name">
          <el-input v-model="form.name" placeholder="请输入登录名称"></el-input>
        </el-form-item>
        <el-form-item label="仓库地址："  prop="address">
          <el-input v-model="form.address" placeholder="请输入仓库地址"></el-input>
        </el-form-item>
        <el-form-item label="类型：" prop="type">
          <el-input v-model="form.type" type="number" placeholder="请输入类型"></el-input>
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input v-model="form.sort"  placeholder="请输入排序"></el-input>
        </el-form-item>
        <el-form-item label="描述：" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-form-item label="负责人：" prop="principal">
          <el-select v-model="form.principal" placeholder="请输入负责人" style="width: 100%">
            <el-option v-for="(key,value) in hashMapStaff" :key="value" :label="key" :value="value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="loadAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>